/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import {
  Form,
  Row,
  Col,
  Input,
  Cascader,
  Tag,
  DatePicker,
  Select,
  Button,
  Modal,
  Divider,
  Tooltip,
  Icon,
  message,
  Radio,
  Switch,
  Transfer,
} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import { isEmpty, isArray, cloneDeep, chunk } from 'lodash'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { reg } from 'utils/util'
// 当前组件样式
import styles from './reportedClientDetailStyle.less'
import Img from 'widget/ImgBoost/ImgBoost'

import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import PopUpSelect from 'widget/PopUpSelect/PopUpSelect'
import Track from 'widget/Map/Track'
import { Grid } from 'widget/Grid/index'
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

const FormItem = Form.Item
const { TextArea } = Input
const InputGroup = Input.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const { RangePicker } = DatePicker;

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 15 },
}
const formItemLayout01 = {
  labelCol: { span: 2},
  wrapperCol: { span: 22 },
}
const formItemLayout02 = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */

const routeView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {loading, pageType, id, modalObj,formData,targetKeys,selectedKeys,houseList, tableData=[],pageConfig={},detailInfo} = modelObj
  // modelObj.xxx获取model中状态机的值

  console.log('routeView', modelObj)
  

  // 点击处理事件
  const clickHandler = (e) => {
    // 分发到model文件中effects的xxx方法
    dispatch({
      type: `${namespace}/xxx`,
      payload: {}
    })
  }
  
  //  公司编号  中介公司名称  合作状态  负责人 合作有效时间   报备人数 成交数
  const columns = [
    {title: '楼盘', dataIndex: '01', key: '01',},
    {title: '客户状态', dataIndex: '02', key: '02',},
    {title: '更新时间', dataIndex: '03', key: '03',
      render: (value,item,index) => {
        return '客户到访有效时间：2018-08-20 03:56:36  至  2018-08-20 23:59:59 '
      }
    },
  ]
  
  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { ...payload }
    })
  }
  // 弹窗
  function inputChange (value, key, index='') {
    if(key!==''){
      formData[key][index] = value
    }else{
      formData[key] = value
    }
    changeState({formData})
  }

  //校验
  function validator(rule, value, callback, type = '') {

  }

  // updateProduct createProduct
  function save() {
    validateFields((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/${{ edit: 'update', add: 'create', detail: '' }[pageType]}`,
          payload: {}
        })
      }
    })
  }

  // 筛选项目名称下拉列表
  function filter(inputValue, path) {
    return (path.some(option => (option.label).toLowerCase().indexOf(inputValue.toLowerCase()) > -1))
  }

  function updateModal () {
    modalObj.visible=!modalObj.visible
    changeState({modalObj})
  }
  
  function  handleChange (nextTargetKeys, direction, moveKeys)  {
    changeState({ targetKeys: nextTargetKeys });
    
    console.log('targetKeys: ', nextTargetKeys);
    console.log('direction: ', direction);
    console.log('moveKeys: ', moveKeys);
  }
  
  function handleSelectChange (sourceSelectedKeys, targetSelectedKeys) {
    changeState({ selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys] });
  }
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: columns,
      pageConfig, tableData
    },
    pageChange: (pageNo, pageSize) => {
      console.log(pageNo, pageSize)
      dispatch({ type: `${namespace}/pageChange`, payload: {pageNo, pageSize } });
    },
    scroll: {x: 800},
    loading
  }
  
  function complement () {
    let arr=cloneDeep(formData.mobile_arr)||[]
    arr.map((item,index)=>{
      if(item.trim()===''){
        arr[index]='*'
      }
    })
    let str=arr.join(',')
    console.log('complement',str)
    updateModal()
  }
  return (
    <div className={cx('public_listMain')}>
      <div className="functionButton">
        <Button type='primary' onClick={() => { save() }}>保存</Button>
        {/*<Button type='primary' onClick={()=>{onCancel()}}>取消</Button>*/}
        {/*<Button type='primary' onClick={() => { }}>导出模板</Button>*/}
      </div>
      <Form>
        <CollapsiblePanels title="报备客户信息" hideUpDownBtn={true}>
          <Row>
            <Col className="col" span={8}>
              <FormItem {...formItemLayout}
                        label="中介公司">
                中原地产
              </FormItem>
            </Col>
            <Col className="col" span={8}>
              <FormItem {...formItemLayout}
                        label="经纪人">
                李源源
              </FormItem>
            </Col>
            <Col className="col" span={8}>
              <FormItem {...formItemLayout}
                        label="报备客户姓名">
                {getFieldDecorator('item_01', {
                  initialValue: formData.consultantMobile,
                  rules: [
                    { required: true,  message: '请输入的姓名' },
                  ],
                })(<Input
                  placeholder={'请输入姓名'}
                  onChange={(e) => { inputChange(e.target.value, 'item_01') }}
                />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col className="col" span={8}>
              <FormItem {...formItemLayout}
                        label="报备电话">
                {getFieldDecorator('item_02', {
                  initialValue: formData.consultantMobile,
                  rules: [
                    { required: true,  message: '请输入正确的号码', pattern: /^1[3456789]\d{9}$/ },
                  ],
                })(
                  <InputGroup compact>
                    <Input
                      disabled
                      style={{width: '70%'}}
                      placeholder="请输入报备电话"
                      onChange={value => { inputChange(value, 'item_02') }}
                    />
                    <Button onClick={()=>{updateModal()}} style={{width: '30%','padding':0}}>补全号码</Button>
                  </InputGroup>)}
              </FormItem>
            </Col>
          </Row>
        </CollapsiblePanels>
        <CollapsiblePanels title="报备楼盘" hideUpDownBtn={true}>
          <Grid {...gridProps} />
        </CollapsiblePanels>
        <CollapsiblePanels title="关联手机" hideUpDownBtn={true}>
          <Row>
            <Col className="col" span={8}>
              <FormItem {...formItemLayout}
                        label="关联人姓名">
                {getFieldDecorator('item_01', {
                  initialValue: formData.consultantMobile,
                  rules: [
                    { required: true,  message: '请输入关联人姓名' },
                  ],
                })(<Input
                  placeholder={'请输入关联人姓名'}
                  onChange={(e) => { inputChange(e.target.value, 'item_01') }}
                />)}
              </FormItem>
            </Col>
            <Col className="col" span={8}>
              <FormItem {...formItemLayout}
                        label="关联人电话">
                {getFieldDecorator('item_01', {
                  initialValue: formData.consultantMobile,
                  rules: [
                    { required: true,  message: '请输入关联人电话' },
                  ],
                })(<Input
                  placeholder={'请输入关联人电话'}
                  onChange={(e) => { inputChange(e.target.value, 'item_01') }}
                />)}
              </FormItem>
            </Col>
            <Col className="col" span={8}>
              <FormItem {...formItemLayout}
                        label="与报备人关系">
                {getFieldDecorator('item_06', {
                  initialValue: formData.consultantMobile,
                  rules: [
                    { required: true,  message: '请选择与报备人关系' },
                  ],
                })(<Select
                  onChange={(e) => { inputChange(e,'item_06') }}
                  placeholder='请选择'>
                  <Option key={'1'} value={'1'}>{'夫妻'}</Option>
                  <Option key={'2'} value={'2'}>{'子女'}</Option>
                  <Option key={'3'} value={'3'}>{'父母'}</Option>
                </Select>)}
              </FormItem>
            </Col>
          </Row>
  
        </CollapsiblePanels>
      </Form>

      <Modal
        title={'补全号码'}
        width='80%'
        // className="pubBiz_CommonModel"
        visible={modalObj.visible}
        onCancel={() => { updateModal() }}
        onOk={() => { complement() }}
        // onOk={}
        // footer={null}
      >
        <Form >
          <Row>
            <Col className="col" span={24}>
              <FormItem {...formItemLayout01}
                        label="手机号">
                {getFieldDecorator('item_01', {
                  // initialValue: formData.consultantMobile,
                  rules: [
                    // { required: true,  message: '请输入手机号' },
                  ],
                })(<div>
                  {
                    formData.mobile_arr.map((item,index)=>{
                      return <Input
                        style={{'padding':'0'}}
                        className={cx('phoneInput')}
                        maxLength={1}
                        disabled={detailInfo.mobile_arr[index]!=='*'}
                        value={item=='*'?'':item}
                        onChange={(e) => {
                          let value=e.target.value
                          if(isNaN(value)){value=''}
                          inputChange(value, 'mobile_arr',index) }
                        }
                      />
                    })
                  }
                </div>)}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
